package com.beta.cust.bind.datasync.utils;

import cn.hutool.crypto.symmetric.SymmetricCrypto;
import lombok.extern.slf4j.Slf4j;

import java.util.Base64;

@Slf4j
public class SM4Helper2 {

    /**
     * 指明加密算法和秘钥
     */
    private static SymmetricCrypto sm4;

    /**
     * 初始化
     */
    public static void init(String encKey) {
        sm4 = new SymmetricCrypto("SM4/ECB/PKCS5Padding", encKey.getBytes());
    }


    //加密为16进制，也可以加密成base64/字节数组
    public static String encryptSm4(byte[] data) {
        byte[] encrypt = sm4.encrypt(data);
        return new String(Base64.getEncoder().encode(encrypt));

    }

    /**
     * 加密
     *
     * @param data
     * @return
     */
    public static String encryptSm4(String data) {
        byte[] encrypt = sm4.encrypt(data);
        byte[] encode = Base64.getUrlEncoder().encode(encrypt);
        return new String(encode);
    }

    /**
     * 解密
     *
     * @param data
     * @return
     */
    public static String decryptSm4(String data) {
        try {
            byte[] decode = Base64.getUrlDecoder().decode(data);
            byte[] decrypt = sm4.decrypt(decode);
            return new String(decrypt);
        } catch (Exception e) {
            log.error("DecryptSm4 error:{}", data, e);
            return "";
        }
    }
}
